"""
author: liuxu
date: 2025/7/8
description: 内存泄漏工具相关bug复测
"""
import os
import allure
import pytest

from common.logger_ctrl import mylogger
from common.ssh_command import exec_cmd
from base_public.testbase import BasePublic
from setting import CPP_DIR


@pytest.mark.medium
@allure.feature('leak-check相关bug')
class TestLeakCheckBugCase(BasePublic):
    def test_bug_98861(self, test_env):
        """
        Bug链接: http://hpczentao.sugon.com/bug-view-98861.html
        标题: dtk-25.04.1内存泄漏检测时出现死锁问题
        问题描述: 1、dlopen打开的动态库中，定义了dlopen返回前自动执行的函数
                2、自动执行的函数中执行了fork函数
                3、fork函数会在清理缓存时，等待函数backtrace_symbles执行完毕
                4、dlopen函数和backtrace_symbles共用了libc的内部锁，dlopen已经提前锁定了内部锁，backtrace_symbles获取内部锁失败，造成死锁等待
        :return:
        """
        # 编译用例
        src_case_dir = os.path.join(CPP_DIR, "bug_case/bug-98861")
        build_path = os.path.join(test_env, "build")
        assert self.create_directory(build_path) is True  # 创建构建用例目录

        compile_cmds = f"""cmake {src_case_dir} && make"""
        for cmd in compile_cmds.split("&&"):
            ret0, output0 = exec_cmd(cmd.strip(), cwd=build_path)  # 工作目录得改到build里
            assert ret0 is True, f"Execute {cmd} failed"

        # 检查是否生成可执行文件
        exe_path = os.path.join(build_path, "myapp")
        assert self.exist_file(exe_path), "The executable file myapp has not been generated"

        # 执行测试命令
        ret, output = exec_cmd(f"hipprof --leak-check {exe_path}", cwd=build_path, timeout=10)
        assert ret is True and self.check_leakcheck_is_success(output)
